//
//  SHKFacebookForm.m
//  ShareKit
//

#import "SHKFormControllerLargeTextField.h"
#import "SHK.h"
#import "SHKFacebook.h"


@interface SHKFormControllerLargeTextField ()

@property (nonatomic, retain) UILabel *counter;
@property BOOL shareIsCancelled;

- (void)layoutCounter;
- (void)updateCounter;
- (void)save;
- (void)keyboardWillShow:(NSNotification *)notification;
- (BOOL)shouldShowCounter;
- (void)ifNoTextDisableSendButton;
- (void)setupBarButtonItems;

@end

@implementation SHKFormControllerLargeTextField

@synthesize delegate, textView, maxTextLength;
@synthesize counter, hasLink, image, imageTextLength;
@synthesize text;
@synthesize shareIsCancelled;

- (void)dealloc 
{
	[textView release];
	[counter release];
	[text release];
	[image release];
	
	[super dealloc];
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil delegate:(id <SHKFormControllerLargeTextFieldDelegate>)aDelegate
{
	if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) 
	{		
		delegate = aDelegate;
		imageTextLength = 0;
		hasLink = NO;
		maxTextLength = 0;
	}
	return self;
}

-(BOOL)shouldAutorotate {
    return NO;
}

- (NSUInteger)supportedInterfaceOrientations {
    return UIInterfaceOrientationMaskPortrait;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation {
    return toInterfaceOrientation == UIInterfaceOrientationPortrait;
}

- (void)loadView 
{
	[super loadView];
	
	self.view.backgroundColor = [UIColor blackColor];
    //self.view.backgroundColor = [UIColor colorWithWhite:1.0 alpha:0.5];
	
	self.textView = [[[UITextView alloc] initWithFrame:CGRectMake(0, 42, 220, 115)] autorelease];
	textView.delegate = self;
	textView.font = [UIFont systemFontOfSize:17];
	//textView.contentInset = UIEdgeInsetsMake(5,5,5,-200);

	textView.backgroundColor = [UIColor clearColor];
    
    
	//textView.autoresizesSubviews = YES;
	textView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
	
	//[self.view addSubview:textView];
    //self.view.backgroundColor = [UIColor whiteColor];  // So we can use any color in IB.
    
    // Add a border and a shadow.
    self.view.layer.cornerRadius = 12.0f;
    self.view.layer.borderWidth = 1.0f;
    //self.view.layer.borderColor = [UIColor colorWithWhite:0.17f alpha:1.0f].CGColor;
    self.view.layer.shadowOpacity = 1.0f;
    self.view.layer.shadowOffset = CGSizeMake(0.0f, 3.0f);
    self.view.layer.shadowRadius = 5.0f;
    
    // Add the background image.
    // We can't put the image on the root view because we need to clip the
    // edges, which we can't do if we want the shadow.
    self.backgroundView = [[[UIView alloc] initWithFrame:CGRectMake(4, 25, 312, 189)] autorelease];
    self.backgroundView.layer.masksToBounds = YES;
    self.backgroundView.layer.cornerRadius = self.view.layer.cornerRadius + 1.0f;
    self.backgroundView.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"DETweetCardBackground"]];
    self.backgroundView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
    [self.view addSubview:self.backgroundView];

    UIButton *btnCancel = [UIButton buttonWithType:UIButtonTypeCustom];
    btnCancel.frame = CGRectMake(8, 7, 63, 30);
    [btnCancel setTitle:@"Cancel" forState:UIControlStateNormal];
    btnCancel.titleLabel.font = [UIFont boldSystemFontOfSize:12];
    [btnCancel setTitleColor:[UIColor colorWithRed:129./255. green:129./255. blue:129./255. alpha:1.f] forState:UIControlStateNormal];
    UIImage *cancelButtonImage = [[UIImage imageNamed:@"DETweetCancelButtonPortrait"] stretchableImageWithLeftCapWidth:4 topCapHeight:0];
    [btnCancel addTarget:self action:@selector(cancel) forControlEvents:UIControlEventTouchUpInside];
    [btnCancel setBackgroundImage:cancelButtonImage forState:UIControlStateNormal];
    //[self.backgroundView insertSubview:btnCancel atIndex:1];
    [self.backgroundView addSubview:btnCancel];
    
    UIButton *btnDone = [UIButton buttonWithType:UIButtonTypeCustom];
    btnDone.frame = CGRectMake(250, 7, 53, 30);
    [btnDone setTitle:@"Send" forState:UIControlStateNormal];
    btnDone.titleLabel.font = [UIFont boldSystemFontOfSize:12];
    UIImage *sendButtonImage = [[UIImage imageNamed:@"DETweetSendButtonPortrait"] stretchableImageWithLeftCapWidth:4 topCapHeight:0];
    [btnDone addTarget:self action:@selector(save) forControlEvents:UIControlEventTouchUpInside];
    [btnDone setBackgroundImage:sendButtonImage forState:UIControlStateNormal];
    //[self.backgroundView insertSubview:btnDone atIndex:1];
    [self.backgroundView addSubview:btnDone];
    
//    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 42, 312, 115)];
//    view.backgroundColor = [UIColor clearColor];
//    [self.backgroundView addSubview:view];
    
    [self.backgroundView addSubview:textView];
    
    SHKTitleLabel *lblTitle = [[SHKTitleLabel alloc] initWithFrame:CGRectMake(0, 10, 312, 24)];
    lblTitle.text = @"Facebook";
    lblTitle.textAlignment = NSTextAlignmentCenter;
    lblTitle.font = [UIFont boldSystemFontOfSize:20];
    lblTitle.textColor = [UIColor colorWithRed:119./255. green:119./255. blue:119./255. alpha:1];
    lblTitle.backgroundColor = [UIColor clearColor];
    [self.backgroundView insertSubview:lblTitle atIndex:1];
    
    UIImageView *imgLine = [[UIImageView alloc] initWithFrame:CGRectMake(0, 41, 312, 3)];
    imgLine.image = [UIImage imageNamed:@"DETweetCardHeaderLine.png"];
    [self.backgroundView addSubview:imgLine];
    
    UIImageView *paperClip = [[UIImageView alloc] initWithFrame:CGRectMake(239, 43, 79, 34)];
    paperClip.image = [UIImage imageNamed:@"DETweetPaperClip"];
    
    
    //[self.backgroundView addSubview:textView];
    
    UIImageView *attachmentFrameView = [[UIImageView alloc] initWithFrame:CGRectMake(223, 55.5, 84, 79)];
    attachmentFrameView.image = [UIImage imageNamed:@"DETweetAttachmentFrame"];
    [self.backgroundView addSubview:attachmentFrameView];
    
    UIImageView *attachmentImageView = [[UIImageView alloc] initWithFrame:CGRectMake(229, 57.5, 71, 71)];
    attachmentImageView.image = image;
    [self.backgroundView addSubview:attachmentImageView];
    [self.backgroundView addSubview:paperClip];
    
    UIButton *btnLogout = [UIButton buttonWithType:UIButtonTypeCustom];
    btnLogout.frame = CGRectMake(230, 140, 80, 30);
    [btnLogout setTitle:@"Log Out" forState:UIControlStateNormal];
    btnLogout.titleLabel.shadowColor = [UIColor blackColor];
    btnLogout.titleLabel.shadowOffset = CGSizeMake(1.0, 1.0);
    [btnLogout setBackgroundColor:[UIColor clearColor]];
    
    [btnLogout addTarget:self action:@selector(onLogOut) forControlEvents:UIControlEventTouchUpInside];
    //[self.backgroundView addSubview:btnLogout];
    [btnLogout setHidden:YES];
    
}

- (void)viewWillAppear:(BOOL)animated
{
	[super viewWillAppear:animated];
	
	// save to set the text now
	textView.text = text;
	
	[self setupBarButtonItems];
}

- (void)viewDidAppear:(BOOL)animated
{
	[super viewDidAppear:animated];	
	
	NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
	[nc addObserver:self selector:@selector(keyboardWillShow:) name: UIKeyboardWillShowNotification object:nil];
	
	[self.textView becomeFirstResponder];
}

- (void)viewDidDisappear:(BOOL)animated
{
	[super viewDidDisappear:animated];	
	
	// Remove observers
	NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
	[nc removeObserver:self name: UIKeyboardWillShowNotification object:nil];
	
	//If user really cancelled share. Sometimes sharers have more stages (e.g Foursquare) and user only returned to previous stage - back on navigation stack.
	if (self.shareIsCancelled) {
        // Remove the SHK view wrapper from the window
        [[SHK currentHelper] viewWasDismissed];
    }
}

- (void)onLogOut {
    [self cancel];
    [SHKFacebook logout];
}

- (void)setupBarButtonItems {
	
	self.navigationItem.leftBarButtonItem = [[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel
																														target:self
																														action:@selector(cancel)] autorelease];
	
	self.navigationItem.rightBarButtonItem = [[[UIBarButtonItem alloc] initWithTitle:SHKLocalizedString(@"Send to %@", [[self.delegate class] sharerTitle]) 
																										style:UIBarButtonItemStyleDone
																									  target:self
																									  action:@selector(save)] autorelease];
}

//- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation 
//{
//	return YES;
//}

#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
- (void)keyboardWillShow:(NSNotification *)notification
{	
	CGRect keyboardFrame;
	CGFloat keyboardHeight;
	
	// 3.2 and above
	if (&UIKeyboardFrameEndUserInfoKey)
	{		
		[[notification.userInfo valueForKey:UIKeyboardFrameEndUserInfoKey] getValue:&keyboardFrame];		
		if ([self interfaceOrientation] == UIDeviceOrientationPortrait || [self interfaceOrientation] == UIDeviceOrientationPortraitUpsideDown) 
			keyboardHeight = keyboardFrame.size.height;
		else
			keyboardHeight = keyboardFrame.size.width;
	}
	
	// < 3.2
	else 
	{
		[[notification.userInfo valueForKey:UIKeyboardBoundsUserInfoKey] getValue:&keyboardFrame];
		keyboardHeight = keyboardFrame.size.height;
	}
	
	// Find the bottom of the screen (accounting for keyboard overlay)
	// This is pretty much only for pagesheet's on the iPad
//	UIInterfaceOrientation orient = [[UIApplication sharedApplication] statusBarOrientation];
//	BOOL inLandscape = orient == UIInterfaceOrientationLandscapeLeft || orient == UIInterfaceOrientationLandscapeRight;
//	BOOL upsideDown = orient == UIInterfaceOrientationPortraitUpsideDown || orient == UIInterfaceOrientationLandscapeRight;
//	
//	CGPoint topOfViewPoint = [self.view convertPoint:CGPointZero toView:nil];
//	CGFloat topOfView = inLandscape ? topOfViewPoint.x : topOfViewPoint.y;
//	
//	CGFloat screenHeight = inLandscape ? [[UIScreen mainScreen] applicationFrame].size.width : [[UIScreen mainScreen] applicationFrame].size.height;
//	
//	CGFloat distFromBottom = screenHeight - ((upsideDown ? screenHeight - topOfView : topOfView ) + self.view.bounds.size.height) + ([UIApplication sharedApplication].statusBarHidden || upsideDown ? 0 : 20);							
//	CGFloat maxViewHeight = self.view.bounds.size.height - keyboardHeight + distFromBottom;
	
	//textView.frame = CGRectMake(0,0,self.view.bounds.size.width,maxViewHeight);
	
	[self layoutCounter];
}
#pragma GCC diagnostic pop

#pragma mark counter updates

- (void)updateCounter
{
	[self ifNoTextDisableSendButton];
	
	if (![self shouldShowCounter]) return;
	
	if (self.counter == nil)
	{
		UILabel *aLabel = [[UILabel alloc] initWithFrame:CGRectZero];
		aLabel.backgroundColor = [UIColor clearColor];
		aLabel.opaque = NO;
		aLabel.font = [UIFont boldSystemFontOfSize:14];
		aLabel.textAlignment = UITextAlignmentRight;		
		aLabel.autoresizesSubviews = YES;
		aLabel.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin;
		self.counter = aLabel;
		[aLabel release];
		
		[self.view addSubview:counter];
		[self layoutCounter];
	}
	
	NSString *count;
    NSInteger countNumber = 0;
    
    if (self.maxTextLength) {
        countNumber = (self.image?(self.maxTextLength - self.imageTextLength):self.maxTextLength) - self.textView.text.length;
        count = [NSString stringWithFormat:@"%i", countNumber];
    } else {
        count = @"";
    }
    //counter.text = [NSString stringWithFormat:@"%@%@", self.image ? [NSString stringWithFormat:@"Image %@ ",countNumber>0?@"+":@""]:@"", count];
 	
	if (countNumber >= 0) {
		
		self.counter.textColor = [UIColor blackColor];        
		if (self.textView.text.length) self.navigationItem.rightBarButtonItem.enabled = YES; 
		
	} else {
		
		self.counter.textColor = [UIColor redColor];
		self.navigationItem.rightBarButtonItem.enabled = NO;
	}  
}

- (void)ifNoTextDisableSendButton {
	
	if (self.textView.text.length) {
		self.navigationItem.rightBarButtonItem.enabled = YES; 
	} else {
		self.navigationItem.rightBarButtonItem.enabled = NO;
	}
}

- (void)layoutCounter
{
	if (![self shouldShowCounter]) return;
	
	counter.frame = CGRectMake(self.textView.bounds.size.width-150-15,
										self.textView.bounds.size.height-15-9,
										150,
										15);
	//self.textView.contentInset = UIEdgeInsetsMake(5,5,32,0);
}

- (BOOL)shouldShowCounter {
	
	if (self.maxTextLength || self.image || self.hasLink) return YES;
	
	return NO;
}

#pragma mark UITextView delegate

- (void)textViewDidBeginEditing:(UITextView *)textView
{
	[self updateCounter];
}

- (void)textViewDidChange:(UITextView *)textView
{
	[self updateCounter];	
}

- (void)textViewDidEndEditing:(UITextView *)textView
{
	[self updateCounter];
}

#pragma mark delegate callbacks 

- (void)cancel
{	
	self.shareIsCancelled = YES;
    [[SHK currentHelper] hideCurrentViewControllerAnimated:YES];
	[self.delegate sendDidCancel];
}

- (void)save
{	    	
	[[SHK currentHelper] hideCurrentViewControllerAnimated:YES]; 
	[self.delegate sendForm:self];
}

@end
